layui.config({
	base : "js/"
}).use(['form','layer','jquery','laypage'],function(){
	var form = layui.form(),
		layer = parent.layer === undefined ? layui.layer : parent.layer,
		laypage = layui.laypage,
		$ = layui.jquery;

	var index_name = sessionStorage.getItem("userInfo");
	var f = JSON.parse(index_name)
	if(f==null||f==""){
		window.location.href = "../login/login.html";
	}

	//加载页面数据
	var adminData = '';
	$.ajax({
		url : "http://localhost:8080/com.3group.personality/admin/selectWebAdmin",
		type : "post",
		dataType : "json",
		success : function(data){
			adminData = data;
			if(window.sessionStorage.getItem("addLinks")){
				var addLinks = window.sessionStorage.getItem("addLinks");
				adminData = JSON.parse(addLinks).concat(adminData);
			}
			//执行加载数据的方法
			linksList();
		}
	})

	//查询
	$(".search_btn").click(function(){
		var adminArray = [];
		if($(".search_input").val() != ''){
			var index = layer.msg('查询中，请稍候',{icon: 16,time:false,shade:0.8});
			setTimeout(function(){
				$.ajax({
					url : "http://localhost:8080/com.3group.personality/admin/selectWebAdmin",
					type : "post",
					dataType : "json",
					success : function(data){
						if(window.sessionStorage.getItem("addLinks")){
							var addLinks = window.sessionStorage.getItem("addLinks");
							adminData = JSON.parse(addLinks).concat(data);
						}else{
							adminData = data;
						}

						for(var i=0;i<adminData.length;i++){
							var adminStr = adminData[i];
							var selectStr = $(".search_input").val();
							function changeStr(data){
								var dataStr = '';
								var showNum = data.split(eval("/"+selectStr+"/ig")).length - 1;
								if(showNum > 1){
									for (var j=0;j<showNum;j++) {
										dataStr += data.split(eval("/"+selectStr+"/ig"))[j] + "<i style='color:#03c339;font-weight:bold;'>" + selectStr + "</i>";
									}
									dataStr += data.split(eval("/"+selectStr+"/ig"))[showNum];
									return dataStr;
								}else{
									dataStr = data.split(eval("/"+selectStr+"/ig"))[0] + "<i style='color:#03c339;font-weight:bold;'>" + selectStr + "</i>" + data.split(eval("/"+selectStr+"/ig"))[1];
									return dataStr;
								}
							}
							console.log("查询为："+adminStr.adminId)
							// console.log("输出："+adminStr.adminId.indexOf(selectStr))
							// console.log("输出值："+adminStr.adminId.indexOf(selectStr))
							//账号
							var adminID=(adminStr.adminId).toString();
							if(adminID.indexOf(selectStr) > -1){
								adminStr["adminId"] = changeStr(adminID);
							}
							/*//真实姓名
                            if(adminStr.name.indexOf(selectStr) > -1){
                                adminStr["name"] = changeStr(adminStr.name);
                            }
                            //性别
                            if(adminStr.sex.indexOf(selectStr) > -1){
                                adminStr["sex"] = changeStr(adminStr.sex);
                            }

                            //邮箱
                            if(adminStr.email.indexOf(selectStr) > -1){
                                adminStr["email"] = changeStr(adminStr.email);
                            }*/
							//电话号码
							if(adminStr.phone.indexOf(selectStr) > -1){
								adminStr["phone"] = changeStr(adminStr.phone);
							}
							/*//账号
							if(adminStr.adminId.indexOf(selectStr) > -1){
								adminStr["adminId"] = changeStr(adminStr.adminId);
							}*/

							/*//备注
							if(adminStr.remake.indexOf(selectStr) > -1){
								adminStr["remake"] = changeStr(adminStr.remake);
							}*/

							if(adminID.indexOf(selectStr)>-1 ||adminStr.phone.indexOf(selectStr)>-1){
								adminArray.push(adminStr);
							}
							/*if(adminStr.adminId.indexOf(selectStr)>-1 || adminStr.name.indexOf(selectStr)>-1 || adminStr.sex.indexOf(selectStr)>-1
                                || adminStr.email.indexOf(selectStr)>-1 || adminStr.phone.indexOf(selectStr)>-1 || adminStr.remake.indexOf(selectStr)>-1){
                                adminArray.push(adminStr);
                            }*/
						}
						adminData = adminArray;
						linksList(adminData);
					}
				})

				layer.close(index);
			},2000);
		}else{
			layer.msg("请输入需要查询的内容");
		}
	})


	//批量删除
	$(".batchDel").click(function(){
		var $checkbox = $('.links_list tbody input[type="checkbox"][name="checked"]');
		var $checked = $('.links_list tbody input[type="checkbox"][name="checked"]:checked');
		if($checkbox.is(":checked")){
			layer.confirm('确定删除选中的信息？',{icon:3, title:'提示信息'},function(index){
				var index = layer.msg('删除中，请稍候',{icon: 16,time:false,shade:0.8});
				setTimeout(function(){
					//删除数据
					for(var j=0;j<$checked.length;j++){
						for(var i=0;i<adminData.length;i++){
							if(adminData[i].adminId == $checked.eq(j).parents("tr").find(".links_del").attr("data-id")){
								$.ajax({
									url: "http://localhost:8080/com.3group.personality/admin/delete?id=" +adminData[i].adminId,
									type: "post",
									dataType: "json",
									success: function (date) {
										console.log(data);
										alert("删除成功")
										usersData.splice(i, 1);
										usersList(date)
										window.location.href = 'allUsers.html'
									}
								})
								adminData.splice(i,1);
								linksList(adminData);
							}
						}
					}
					$('.links_list thead input[type="checkbox"]').prop("checked",false);
					form.render();
					layer.close(index);
					layer.msg("删除成功");
				},2000);
			})
		}else{
			layer.msg("请选择需要删除的文章");
		}
	})

	//全选
	form.on('checkbox(allChoose)', function(data){
		var child = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="show"])');
		child.each(function(index, item){
			item.checked = data.elem.checked;
		});
		form.render('checkbox');
	});

	//通过判断文章是否全部选中来确定全选按钮是否选中
	form.on("checkbox(choose)",function(data){
		var child = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="show"])');
		var childChecked = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="show"]):checked')
		data.elem.checked;
		if(childChecked.length == child.length){
			$(data.elem).parents('table').find('thead input#allChoose').get(0).checked = true;
		}else{
			$(data.elem).parents('table').find('thead input#allChoose').get(0).checked = false;
		}
		form.render('checkbox');
	})

	//添加管理员
	$(".linksAdd_btn").click(function(){
		var index = layui.layer.open({
			title : "添加管理员",
			type : 2,
			content : "linksAdd.html",
			success : function(layero, index){
				setTimeout(function(){
					layui.layer.tips('点击此处返回友链列表', '.layui-layer-setwin .layui-layer-close', {
						tips: 3
					});
				},500)
			}
		})
		//改变窗口大小时，重置弹窗的高度，防止超出可视区域（如F12调出debug的操作）
		$(window).resize(function(){
			layui.layer.full(index);
		})
		layui.layer.full(index);
	})

	//操作
	$("body").on("click",".links_del",function(){  //删除
		var _this = $(this);
		layer.confirm('确定删除此信息？',{icon:3, title:'提示信息'},function(index){
			//_this.parents("tr").remove();
			for(var i=0;i<adminData.length;i++){
				if(adminData[i].adminId == _this.attr("data-id")){
					$.ajax({
						url: "http://localhost:8080/com.3group.personality/admin/delete?id=" + _this.attr("data-id"),
						type: "post",
						dataType: "json",
						success: function (date) {
							console.log("返回值为"+data);
							alert("删除成功")
							usersData.splice(i, 1);
							usersList(date)
							window.location.href = "linkList.html"
						}
					})

					adminData.splice(i,1);
					linksList(adminData);
				}
			}
			layer.msg("删除成功");
			layer.close(index);
		});
	})

	function linksList(that){
		//渲染数据
		function renderDate(data,curr){
			var dataHtml = '';
			if(!that){
				currData = adminData.concat().splice(curr*nums-nums, nums);
			}else{
				currData = that.concat().splice(curr*nums-nums, nums);
			}
			if(currData.length != 0){
				for(var i=0;i<currData.length;i++){
					dataHtml += '<tr>'
						+'<td><input type="checkbox" name="checked" lay-skin="primary" lay-filter="choose"></td>'
						+'<td>'+currData[i].adminId+'</td>'
						+'<td>'+currData[i].name+'</td>'
						+'<td>'+currData[i].email+'</td>'
						+'<td>'+currData[i].phone+'</td>'
						+'<td>'+currData[i].remake+'</td>'
						+'<td>'

						+  '<a class="layui-btn layui-btn-danger layui-btn-mini links_del" data-id="'+data[i].adminId+'"><i class="layui-icon">&#xe640;</i> 删除</a>'
						+'</td>'
						+'</tr>';
				}
			}else{
				dataHtml = '<tr><td colspan="7">暂无数据</td></tr>';
			}
			return dataHtml;
		}

		//分页
		var nums = 13; //每页出现的数据量
		if(that){
			adminData = that;
		}
		laypage({
			cont : "page",
			pages : Math.ceil(adminData.length/nums),
			jump : function(obj){
				$(".links_content").html(renderDate(adminData,obj.curr));
				$('.links_list thead input[type="checkbox"]').prop("checked",false);
				form.render();
			}
		})
	}
})

